import nodemailer from 'nodemailer'
import path from 'path'
import fs from 'fs'
export const sendEmail = async ctx => {
  try {
    const source = replaceFields(ctx)

    const info = await send(ctx.request.query.email, source)
    ctx.body = {
      success: true,
      data: info
    }
  } catch (err) {
    ctx.body = {
      success: false
    }
  }
}

/** 2019/2/17
 * @Author: 刘宇琳
 * @Desc: 发送邮件
 */
function send(email, source) {
  return new Promise((resolve, reject) => {
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
      host: 'smtp.qq.com',
      port: 465,
      secure: true, // true for 465, false for other ports
      auth: {
        user: '122687220', // generated ethereal user
        pass: 'yxqryogacncqbgjg' // generated ethereal password
      }
    })

    // setup email data with unicode symbols
    let mailOptions = {
      from: '"zoomlion" <liuyulin_ios@foxmail.com>', // sender address
      to: email, // list of receivers
      subject: '面试邀请函', // Subject line
      html: source // html body
    }

    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        reject(error)
      } else {
        resolve({
          id: info.messageId,
          url: nodemailer.getTestMessageUrl(info)
        })
      }
    })
  })
}

/** 2019/2/17
 * @Author: 刘宇琳
 * @Desc: 替换邮件字段
 */
function replaceFields(ctx) {
  const name = ctx.request.query.name
  const job = ctx.request.query.job
  const time = ctx.request.query.time
  const contactNumber = ctx.request.query.contactNumber

  // 获取编码后的html资源
  let source = fs.readFileSync(
    path.resolve(__dirname, '../templates/Notify/index.html'),
    'utf8'
  )
  source = source.replace('{{name}}', name)
  source = source.replace('{{job}}', job)
  source = source.replace('{{time}}', time)
  source = source.replace('{{contact-number}}', contactNumber)

  return source
}
